import { useSetState } from 'ahooks';
import { MutableRefObject, useRef } from 'react';

declare type StateType = {
  /**
   * 当前页码
   */
  page: number;
  /**
   * 是否在请求中
   */
  isLoading: boolean;
  /**
   * 是否请求完所有数据
   */
  isEnd: boolean;
  /**
   * 是否开启内部状态 处理不请求时隐藏显示
   */
  isStart: boolean;
};

declare type UseLoadMoreType = {
  loadMoreStateRef: MutableRefObject<StateType>;
  /**
   * 状态
   */
  loadMoreState: StateType;
  /**
   * 设置请求中
   */
  loadMoreShowLoading: () => void;
  /**
   * 设置请求介绍
   */
  loadMoreHideLoading: () => void;
  /**
   * 验证是否在请求中
   */
  loadMoreCheckLoading: (restLoad?: boolean) => boolean;
  /**
   * 请求后判断数据是否全部完成
   */
  loadMoreLoadHandle: (total: number, dataLength: number) => void;
  /**
   * 重置请求状态
   */
  loadMoreReset: (isLoading?: boolean, isEnd?: boolean) => void;
  /**
   * 设置为数据请求完成
   */
  loadMoreDone: () => void;
};

const defaultStateType = {
  page: 1,
  isStart: false,
  isLoading: false,
  isEnd: false,
};

export default (): UseLoadMoreType => {
  const [state, setState] = useSetState<StateType>(defaultStateType);
  const stateRef = useRef<StateType>(defaultStateType);

  const setStateFn = (stateObj: any, refreshType?: any) => {
    stateRef.current = { ...stateRef.current, ...stateObj, refreshType };
  };

  const loadMoreLoadHandle = (total: number, dataLength: number) => {
    setState((prev: StateType) => {
      const newState = { page: prev.page + 1, isStart: true };
      setStateFn(newState, 1);
      return newState;
    });

    if (!total || total <= dataLength) {
      const newState = { isEnd: true };
      setStateFn(newState, 2);
      setState(newState);
    }
  };

  const loadMoreShowLoading = () => {
    const newState = { isLoading: true, isStart: true };
    setStateFn(newState, 3);
    setState(newState);
  };

  const loadMoreHideLoading = () => {
    const newState = { isLoading: false, isStart: true };
    setStateFn(newState, 4);
    setState(newState);
  };

  const loadMoreDone = () => {
    const newState = { isLoading: false, isEnd: true };
    setStateFn(newState, 5);
    setState(newState);
  };

  const loadMoreReset = (isLoading: boolean = false, isEnd: boolean = false) => {
    const newState = { isLoading: isLoading, isEnd: isEnd, page: 1, isStart: true };
    setStateFn(newState, 6);
    setState(newState);
  };
  /**
   * 是否可以继续执行请求
   */
  const loadMoreCheckLoading = (restLoad: boolean = false): boolean => {
    // 如果是刷新页面
    if (restLoad && !stateRef.current.isLoading) {
      return true;
    }

    if (stateRef.current.isLoading || stateRef.current.isEnd) {
      return false;
    }
    return true;
  };

  return {
    loadMoreStateRef: stateRef,
    loadMoreState: state,
    loadMoreShowLoading,
    loadMoreHideLoading,
    loadMoreCheckLoading,
    loadMoreLoadHandle,
    loadMoreReset,
    loadMoreDone,
  };
};
